package com.bham.teamwork.filter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.bham.teamwork.utils.SecureTokenUtil;
import com.bham.teamwork.utils.SqlXssUtil;

/**
 * 
 * @author Federico Bacci
 * @author Alessandro Pozzer
 * @author RuJia Li 
 * 
 */
public class XssSqlFilter implements Filter {
	private static Logger logger=Logger.getLogger(XssSqlFilter.class);


	private String[] xssSqlExceptionUrls=null;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	    String xssSqlExceptionUrlStr=filterConfig.getInitParameter("xssSqlExceptionUrl");
	    if((xssSqlExceptionUrlStr != null)&& xssSqlExceptionUrlStr.length() != 0){
	    	xssSqlExceptionUrls=xssSqlExceptionUrlStr.split(";");
	    }
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) {
		
		try {
			if(xssSqlExceptionUrls!=null && xssSqlExceptionUrls.length>0){
				String requestURI=((HttpServletRequest)request).getRequestURI();
				if(!SecureTokenUtil.isExceptionURI(requestURI, xssSqlExceptionUrls)){ //Blacklisted data
					startValidateData(request,response,chain);
				}else{
					chain.doFilter(request, response);
					return;
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	@Override
	public void destroy() {
	}

	public static void startValidateData(ServletRequest request, ServletResponse response, FilterChain chain) throws Exception{
		if(!SqlXssUtil.validataRequestHasAttcak(request, response)) { //There is no security risk
			chain.doFilter(request, response);
			return;
		}else{
			redirect2NotSecurePage(request,response);  //There is a security risk, jump directly to the insecure interface
			return;
		}
	}





	
	/**
	 *  forward to NotSecurePage
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private static void  redirect2NotSecurePage(ServletRequest request, ServletResponse response) throws IOException{
		HttpServletRequest req  = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		String requestWith = req.getHeader("x-requested-with");  
		String contentType = req.getHeader("x-content-type");  
		String contextPath = req.getContextPath();
		contentType = (contentType == null)? "":contentType;
		if(requestWith==null){    
			resp.sendRedirect(contextPath+"/unsecure.jsp?url="+ SecureTokenUtil.getRequestUrl((HttpServletRequest) request));
		}else{ 
			if(contentType.equalsIgnoreCase("xml")){ 
				resp.setHeader("Content-Type", "text/xml;charset=UTF-8");
				resp.setCharacterEncoding("UTF-8");
				resp.getWriter().print("<root><data_id></data_id><data_desc></data_desc><errorCode>101</errorCode><errorInfo>There is a security risk for your current operation!</errorInfo><data></data><callback></callback></root>");
			}else{ 
				resp.setHeader("Content-Type", "text/html;charset=UTF-8");
				resp.setCharacterEncoding("UTF-8");
				resp.getWriter().print("{'data_id':'','data_desc':'','errorCode':101,'errorInfo':'There is a security risk for your current operation!','data':[],'callback':''}");
			}
		}
	}
	
	
	



}
